class User < ApplicationRecord
  has_many :bikes
  attr_accessor :re_password, :new_password
  mount_uploader :avatar, AvatarUploader
  before_save :update_salt
  scope :registered, -> { where(status: 1) }

  def token
    Digest::MD5.hexdigest("#{id}|#{salt}")
  end

  def as_json
    super(except: [:created_at, :updated_at, :salt, :password, :avatar]).merge(avatar: avatar.blank? ? "" : avatar.url.prepend($img_host), bike: bikes.map(&:as_json), token: token)
  end

  protected
  def update_salt
    if new_password.blank?
      #手机直接修改
      unless password.eql?(password_was)
        puts password.eql?(re_password)
        if password.eql?(re_password)
          salt_arr = %w"a b c d e f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9"
          self.salt = salt_arr.sample(18).join
          self.password = Digest::MD5.hexdigest("#{password}|#{self.salt}")
        else
          errors.add(:password, "您２次输入的密码不一致")
          throw(:abort)
        end
      end
    else
      #原密码修改
      if password_was.eql?(Digest::MD5.hexdigest("#{password}|#{self.salt}"))
        if new_password.eql?(re_password)
          salt_arr = %w"a b c d e f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9"
          self.salt = salt_arr.sample(18).join
          self.password = Digest::MD5.hexdigest("#{new_password}|#{self.salt}")
        else
          errors.add(:password, "您２次输入的密码不一致")
          throw(:abort)
        end
      else
        errors.add(:password, "您输入的原密码不正确")
        throw(:abort)
      end
    end
  end
end
